package com.hitnet.hitnet;

/**
 * Created by juwenz on 15/5/3.
 */
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.params.HttpClientParams;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.params.HttpProtocolParams;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.SocketTimeoutException;
import java.net.URL;
import java.util.List;

public class HttpHandle {
    private HttpParams httpParams;
    private HttpClient httpClient;
    public String executeHttpGet(String urlStr) throws Exception{
        return httpGet(urlStr, null);
    }

    public String httpGet(String urlStr,HttpURLConnection conn)throws Exception{
        String result = null;
        URL url = null;
        HttpURLConnection connection = null;
        InputStreamReader in = null;
        try {
            url = new URL(urlStr);
            connection = (HttpURLConnection) url.openConnection();
            connection.setConnectTimeout(15000);
            connection.setReadTimeout(15000);
            connection.setUseCaches(false);
            connection.connect();
            conn = connection;
            if(200 == connection.getResponseCode()){
                in = new InputStreamReader(connection.getInputStream());
                BufferedReader bufferedReader = new BufferedReader(in);
                StringBuffer strBuffer = new StringBuffer();
                String line = null;
                while ((line = bufferedReader.readLine()) != null) {
                    strBuffer.append(line);
                }
                result = strBuffer.toString();
            }
            else if(connection.getResponseCode() == HttpURLConnection.HTTP_CLIENT_TIMEOUT){
                throw new Exception("∂‘≤ª∆£¨«Î«Û≥¨ ±");
            }else if(connection.getResponseCode() == HttpURLConnection.HTTP_NOT_FOUND){
                throw new Exception("∂‘≤ª∆£¨«Î«Û◊ ‘¥≤ª¥Ê‘⁄");
            }
        } catch (SocketTimeoutException e) {
            throw new Exception("∂‘≤ª∆£¨«Î«Û≥¨ ±");
        }catch(Exception e){
            throw new Exception("∂‘≤ª∆£¨«Î«Û ß∞‹");
        }
        finally {
            if (connection != null) {
                connection.disconnect();
            }
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

        }
        return result;
    }


    public String doPost(String url, List<NameValuePair> params) {

	        /* Ω®¡¢HTTPPost∂‘œÛ */
        HttpPost httpRequest = new HttpPost(url);

        String strResult = "doPostError";

        try {
	            /* ÃÌº”«Î«Û≤Œ ˝µΩ«Î«Û∂‘œÛ */
            httpRequest.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
	            /* ∑¢ÀÕ«Î«Û≤¢µ»¥˝œÏ”¶ */
            if(httpClient == null)
                getHttpClient();
            HttpResponse httpResponse = httpClient.execute(httpRequest);
	            /* »Ù◊¥Ã¨¬ÎŒ™200 ok */
            if (httpResponse.getStatusLine().getStatusCode() == 200) {
	                /* ∂¡∑µªÿ ˝æ› */
                strResult = EntityUtils.toString(httpResponse.getEntity());

            } else {
                strResult = EntityUtils.toString(httpResponse.getEntity());
            }
        } catch (ClientProtocolException e) {
            strResult = e.getMessage().toString();
            e.printStackTrace();
        } catch (IOException e) {
            strResult = e.getMessage().toString();
            e.printStackTrace();
        } catch (Exception e) {
            strResult = e.getMessage().toString();
            e.printStackTrace();
        }

        return strResult;
    }

    public HttpClient getHttpClient() {

        // ¥¥Ω® HttpParams “‘”√¿¥…Ë÷√ HTTP ≤Œ ˝£®’‚“ª≤ø∑÷≤ª «±ÿ–Ëµƒ£©

        this.httpParams = new BasicHttpParams();

        // …Ë÷√¡¨Ω”≥¨ ±∫Õ Socket ≥¨ ±£¨“‘º∞ Socket ª∫¥Ê¥Û–°

        HttpConnectionParams.setConnectionTimeout(httpParams, 20 * 1000);

        HttpConnectionParams.setSoTimeout(httpParams, 20 * 1000);

        HttpConnectionParams.setSocketBufferSize(httpParams, 8192);

        // …Ë÷√÷ÿ∂®œÚ£¨»± °Œ™ true

        HttpClientParams.setRedirecting(httpParams, true);

        // …Ë÷√ user agent

        //String userAgent = "Mozilla/5.0 (Windows; U; Windows NT 5.1; zh-CN; rv:1.9.2) Gecko/20100115 Firefox/3.6";
        String userAgent = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2311.135 Safari/537.36";
        HttpProtocolParams.setUserAgent(httpParams, userAgent);

        // ¥¥Ω®“ª∏ˆ HttpClient  µ¿˝

        // ◊¢“‚ HttpClient httpClient = new HttpClient();  «Commons HttpClient

        // ÷–µƒ”√∑®£¨‘⁄ Android 1.5 ÷–Œ“√«–Ë“™ π”√ Apache µƒ»± ° µœ÷ DefaultHttpClient

        httpClient = new DefaultHttpClient(httpParams);

        return httpClient;
    }
}
